package com.yaoweigroup.community.ui.my;

import java.io.File;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.yaoweigroup.community.R;
import com.yaoweigroup.community.config.Constant;
import com.yaoweigroup.community.config.Urls;
import com.yaoweigroup.community.dialog.DialogCallBack;
import com.yaoweigroup.community.enity.Version;
import com.yaoweigroup.community.ui.MainTabActivity;
import com.yaoweigroup.community.util.ApkDownloadUtil;
import com.yaoweigroup.community.util.DialogUtil;
import com.yaoweigroup.community.util.LogUtil;
import com.yaoweigroup.community.util.SharePreferenceUtil;
import com.yaoweigroup.community.util.UtilHttp;
import com.yaoweigroup.community.util.VersionUtil;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 设置信息
 * 
 * @author xi
 * 
 */
public class SettingActivity extends Activity implements OnClickListener {

	private RelativeLayout left_rl;
	private RelativeLayout setting_rl;
	private SharePreferenceUtil util;
	private TextView version_tv;
	private RelativeLayout version_rl;
	private ObjectMapper mapper;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting);
		mapper = new ObjectMapper();
		util = new SharePreferenceUtil(this, Constant.prf);
		left_rl = (RelativeLayout) findViewById(R.id.left_rl);
		left_rl.setOnClickListener(this);

		version_rl = (RelativeLayout) findViewById(R.id.version_rl);
		version_rl.setOnClickListener(this);
		setting_rl = (RelativeLayout) findViewById(R.id.setting_rl);
		setting_rl.setOnClickListener(this);

		version_tv = (TextView) findViewById(R.id.version_tv);
		try {
			version_tv.setText("版本号:V" + VersionUtil.getVersionName(this));

		} catch (Exception e) {

		}
	}

	private Intent intent;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.left_rl:
			finish();
			break;
		case R.id.setting_rl:
			intent = new Intent(this, AboutActivity.class);
			startActivity(intent);
			break;
		case R.id.version_rl:
			checkVersion();
			Toast.makeText(this, "版本检测中,请稍等!", 500).show();
			break;
		}

	}

	public final int GET_VERSION_FAIL = 0x2210;
	public final int GET_VERSION_SUCCESS = GET_VERSION_FAIL + 1;
	public final int NEW_VERSION = GET_VERSION_SUCCESS + 2;
	public final int NO_NEW_VERSION = GET_VERSION_SUCCESS + 3;
	private Version version;

	private void checkVersion() {
		HttpUtils http = UtilHttp.getHttpUtils(this);
		http.send(HttpRequest.HttpMethod.POST, Urls.version,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {

						handler.sendEmptyMessage(GET_VERSION_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {

						String result = arg0.result;
						LogUtil.d("wxf", "version =" + result);
						try {
							JSONObject obj = new JSONObject(arg0.result);
							int state = obj.getInt("state");
							String data = obj.getString("data");
							if (state == 200) {
								version = mapper.readValue(data,
										new TypeReference<Version>() {
										});
								int currentCode = VersionUtil
										.getCurrentLocalVersion(SettingActivity.this);
								if (version.getVersionCode() > currentCode) {
									Message msg = handler.obtainMessage();
									msg.what = NEW_VERSION;
									handler.sendMessage(msg);
								} else {
									Message msg = handler.obtainMessage();
									msg.what = NO_NEW_VERSION;
									handler.sendMessage(msg);
								}
							} else {
								handler.sendEmptyMessage(GET_VERSION_FAIL);

							}
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(GET_VERSION_FAIL);

						}
					}

				});

	}

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GET_VERSION_FAIL:
				Toast.makeText(SettingActivity.this, "获取失败", 500).show();
				break;
			case GET_VERSION_SUCCESS:

				break;
			case NO_NEW_VERSION:
				Toast.makeText(SettingActivity.this, "已经是最新版本", 500).show();

				break;
			case NEW_VERSION:
				DialogUtil.versionDialog(SettingActivity.this,
						version.getVersionDes(), new DialogCallBack() {

							@Override
							public void viewClick() {

							}

							@Override
							public void ok() {
								try {
									ApkDownloadUtil util = new ApkDownloadUtil(
											getApplicationContext(),
											handler,
											version.getApkUrl(),
											String.valueOf(getText(R.string.app_name)
													+ "_"
													+ VersionUtil
															.getVersionName(SettingActivity.this)));
									util.start();
								} catch (Exception e) {
								}
							}

							@Override
							public void init(Object obj) {

							}

							@Override
							public void cancel() {

							}
						}, "升级", "取消");
				break;
			case ApkDownloadUtil.MSG_DOWNING:
				Toast.makeText(getApplicationContext(), R.string.downloadStart,
						Toast.LENGTH_LONG).show();
				break;
			case ApkDownloadUtil.MSG_FINISH:
				String path = (String) msg.obj;
				installAPK(path);
				break;
			case ApkDownloadUtil.MSG_FAILURE:
				Toast.makeText(getApplicationContext(),
						R.string.downloadFailure, Toast.LENGTH_LONG).show();
				break;
			}

		};
	};

	private void installAPK(String path) {

		Uri uri = Uri.fromFile(new File(path));
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		startActivity(intent);
	}
}
